import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.util.List;


public class ZkClient {

    private String connectString = "47.108.48.236:2182";
    private int sessionTimeout = 300000;
    private ZooKeeper zooKeeper;

    /**
     * 连接 zookeeper
     * @throws Exception
     */
    @Before
    public void init() throws Exception {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            /**
             *
             * @param event: 监听事件
             */
            @Override
            public void process(WatchedEvent event) {
                System.out.println("Received event: " + event);
                List<String> childrens = null;
                try {
                    childrens = zooKeeper.getChildren("/", true);
                    for (String children: childrens) {
                        System.out.println(children);
                    }
                    System.out.println("-----------------");
                } catch (KeeperException e) {
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    /**
     * 创建节点
     * @throws InterruptedException
     * @throws KeeperException
     */
    @Test
    public void create() throws InterruptedException, KeeperException {
        String path = "/h1";
        String nodeCreate = zooKeeper.create(path, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("Node created: " + nodeCreate);
    }

    /**
     * 获取子节点
     * @throws InterruptedException
     * @throws KeeperException
     */
    @Test
    public void watchChild() throws InterruptedException, KeeperException {
//        List<String>  childrens = zooKeeper.getChildren("/", true);
//        for (String children: childrens) {
//            System.out.println(children);
//        }
        Thread.sleep(Long.MAX_VALUE);
    }


    /**
     * 判断节点是否存在
     * @throws InterruptedException
     * @throws KeeperException
     */
    @Test
    public void exists() throws InterruptedException, KeeperException {
        Stat exists = zooKeeper.exists("/aaa", false);
        System.out.println(exists);
    }
}